package io.gitee.macxiang.sql;

import java.util.HashMap;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import com.zaxxer.hikari.HikariDataSource;

import io.gitee.macxiang.utils.Datas;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = false)
@Component
@EnableConfigurationProperties(SqlConfig.class)
@PropertySource("classpath:application.yml")
@ConfigurationProperties(prefix = "mac.sql")
public class SqlConfig extends HikariDataSource {
  private String database;
  private String addr;
  private int port;
  public int maxcount = 100;
  final public HashMap<String, HikariDataSource> ds = new HashMap<>();

  public HikariDataSource dataSource(String database, String addr, Integer port) {
    if (Datas.isEmpty(database)) {
      database = this.database;
    }
    this.database = database;
    if (Datas.isEmpty(database)) {
      return null;
    }

    if (Datas.isEmpty(addr)) {
      addr = this.addr == null ? "localhost" : this.addr;
    }
    this.addr = addr;
    if (port == null || port < 1 || port > 65535) {
      port = this.port < 1 || this.port > 65535 ? 3306 : this.port;
    }
    this.port = port;
    if (this.getDriverClassName() == null) {
      setDriverClassName("com.mysql.cj.jdbc.Driver");
    }
    String url = String.format(
        "jdbc:mysql://%s:%s/%s?useSSL=false&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8",
        addr, port, database);
    this.setJdbcUrl(url);
    if (!ds.containsKey(url)) {
      try {
        ds.put(url, new HikariDataSource(this));
      } catch (Exception e) {
        System.err.println("数据库连接失败");
      }
    }
    return ds.get(url);
  }

  public HikariDataSource dataSource(String database) {
    return dataSource(database, addr, port);
  }

  public HikariDataSource dataSource() {
    return dataSource(database, addr, port);
  }
}
